package com.tmptSource.controller.action;

import com.opensymphony.xwork2.ActionSupport;
import com.tmpt.dto.Result;
import com.tmptSource.dto.${classNameFirstWordUpper}Dto;
import com.tmptSource.dto.PageDto;
import com.tmptSource.service.intf.I${classNameFirstWordUpper}Service;
import com.tmpt.utils.*;
import lombok.Getter;
import lombok.Setter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Getter
@Setter
@Controller(value="${classNameFirstWordLower}Action")
@Scope("prototype")
public class ${classNameFirstWordUpper}Action extends ActionSupport {
	private Logger log = Logger.getLogger(this.getClass());


	//------------
	//与页面交互的分页和排序
	//--------------
	private int page=0;
	private int rows=0;
	private String sortColumn;
	private String sortOrder;

	//------------
	//与页面交互的业务数据
	//--------------
	<#list columnList as column>
    private String ${column.propertyName};
	<#if column.columnType4JavaEncap=='Timestamp' || column.queryType=='between'>
	private String ${column.propertyName}_Start;
	private String ${column.propertyName}_End;
	</#if>
	</#list>

	//返回结果
	private String result;
	//返回结果
	private List<Map<String,Object>> jsonArrayResult = new ArrayList<Map<String,Object>>();


	@Resource
	private I${classNameFirstWordUpper}Service ${classNameFirstWordLower}Service;


	/**
	* 分页查询列表
	* @return
	*/
	public String queryListBySearch(){
		try {

			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();

			//查询参数
			//分页/排序查询条件
			PageDto pageDto = new PageDto();
			<#--if(sortColumn.endsWith("_Str")){
				sortColumn = sortColumn.substring(0,sortColumn.indexOf("_Str"));
			}-->
			//默认主键desc
			if(StringUtils.isNull(sortColumn)){
				sortColumn = "${primaryKey}";
				sortOrder = "desc";
			}
			pageDto.setPageCurrent(page-1);
			pageDto.setPageSize(rows);
			pageDto.setSortColumn(sortColumn);
			pageDto.setSortOrder(sortOrder);

			//查询条件
			${classNameFirstWordUpper}Dto ${classNameFirstWordLower}Param = new ${classNameFirstWordUpper}Dto();
			<#list conditionColumnMapList as conditionColumn>
			<#--//日期格式转化-->
			<#if  conditionColumn.columnType4JavaEncap=='Timestamp'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}_Start(this.${conditionColumn.propertyName}_Start);
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}_End(this.${conditionColumn.propertyName}_End);
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName});
			<#--//between-->
			<#elseif conditionColumn.queryType=='between'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}_Start(this.${conditionColumn.propertyName}_Start);
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}_End(this.${conditionColumn.propertyName}_End);
			<#--//int,long格式转化-->
			<#elseif conditionColumn.columnType4JavaEncap=='Integer'
					|| conditionColumn.columnType4JavaEncap=='Long'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName});
			<#elseif conditionColumn.columnType4JavaEncap=='String'>
			<#--son if begen-->
			<#if conditionColumn.queryType=='left like'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName}!=null?"%"+this.${conditionColumn.propertyName}:null);
			<#elseif conditionColumn.queryType=='right like'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName}!=null?this.${conditionColumn.propertyName}+"%":null);
			<#elseif conditionColumn.queryType=='like'>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName}!=null?"%"+this.${conditionColumn.propertyName}+"%":null);
			<#else >
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName});
			</#if>
			<#--son if end-->
			<#else>
			${classNameFirstWordLower}Param.set${conditionColumn.propertyNameFirstWordUpper}(this.${conditionColumn.propertyName});
			</#if>
			</#list>

			//data limit control
			String requireUrl = request.getRequestURI().toString();
			String queryString = request.getQueryString();
			String contextPath = request.getContextPath();
			//data limit parameters
			String userId = WebUtils.getUserId();
			Map<String,Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userId", userId);
			paramMap.put("contextPath", contextPath);
			paramMap.put("requireUrl", requireUrl);
			paramMap.put("queryString", queryString);

			//调用远程服务
			Result<${classNameFirstWordUpper}Dto> resultObj =  ${classNameFirstWordLower}Service.pagination(${classNameFirstWordLower}Param,pageDto,paramMap);
			if(!resultObj.isSuccess()){
				this.result = "error:"+resultObj.getContent();
				JsonPaginationUtils.responseWriter(response, this.result);
				return "jsonResult";
			}
			Map<String,Object> resultMap = resultObj.getResultMap();

			//分页记录
			List<${classNameFirstWordUpper}Dto> list = (List<${classNameFirstWordUpper}Dto>)resultMap.get("rows");
			JSONArray jsonArrayRows = JSONArray.fromObject(list);

			//分页总记录数
			int total = 0;
			if(resultMap.get("total") != null){
				total = Integer.parseInt(resultMap.get("total").toString());
			}

			//分页合计（select '合计' as c1, sum(balance) as c2 ....）
			JSONArray jsonArrayFooter = null;
			if(resultMap.get("footer")!=null){
				jsonArrayFooter = JSONArray.fromObject(resultMap.get("footer"));
			}

			JSONObject json = new JSONObject();
			json.put("total", total);
			json.put("rows", jsonArrayRows);
			//json.put("reportSqlString",reportSqlString);
			if(jsonArrayFooter!=null){
				json.put("footer", jsonArrayFooter);
			}

			this.result = json.toString();
			JsonPaginationUtils.responseWriter(response, this.result);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "jsonResult";
	}

	/**
	* 伪删除数据
	* @return
	*/
	public String removeData(){
		Result resultObj = new Result();
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();

			//参数
			String adminMan = WebUtils.getUsername();//加入管理员

			//调用远程服务
			resultObj =  ${classNameFirstWordLower}Service.deleteById(Long.valueOf(${primaryKey_PropertyFormat}),adminMan);
			<#--if(!resultObj.isSuccess()){
				this.result = "error:"+resultObj.getContent();
				JsonPaginationUtils.responseWriter(response, this.result);
				return "jsonResult";
			}-->
			this.jsonArrayResult.add(resultObj.getResultMap());

		} catch (Exception e) {
			e.printStackTrace();
			resultObj.fault("error:系统出错:"+e.getLocalizedMessage());
			this.jsonArrayResult.add(resultObj.getResultMap());
		}

		return "jsonArray";
	}


	/**
	* 编辑数据
	* @return
	*/
	public String editData(){
		Result<${classNameFirstWordUpper}Dto> resultObj = new Result();
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();

			//参数
			${classNameFirstWordUpper}Dto ${classNameFirstWordLower}Dto = new ${classNameFirstWordUpper}Dto();
			String adminMan = WebUtils.getUsername();//加入管理员
            String userId = WebUtils.getUserId();
			${classNameFirstWordLower}Dto.setModifymanId(userId);
			${classNameFirstWordLower}Dto.setModifyman(adminMan);
			${classNameFirstWordLower}Dto.setCompanyId(WebUtils.getCompanyId());
			<#if primaryKeyDbTypeLower=='int' || primaryKeyDbTypeLower=='long' || primaryKeyDbTypeLower=='bigint'>
			${classNameFirstWordLower}Dto.set${primaryKeyFirstWordUpper}(this.${primaryKey});
			</#if>
			//编辑数据
			<#list columnCanAddList as column>
			${classNameFirstWordLower}Dto.set${column.propertyNameFirstWordUpper}(this.${column.propertyName});
			</#list>

			//调用远程服务
			resultObj =  ${classNameFirstWordLower}Service.editData(${classNameFirstWordLower}Dto);
			<#--if(!resultObj.isSuccess()){
				this.result = "error:"+resultObj.getContent();
				JsonPaginationUtils.responseWriter(response, this.result);
				return "jsonResult";
			}-->
			this.jsonArrayResult.add(resultObj.getResultMap());

		} catch (Exception e) {
			e.printStackTrace();
			resultObj.fault("error:系统出错:"+e.getLocalizedMessage());
			this.jsonArrayResult.add(resultObj.getResultMap());
		}

		return "jsonArray";
	}

	/**
	* 添加数据
	* @return
	*/
	public String addData(){
		Result<${classNameFirstWordUpper}Dto> resultObj = new Result();
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();

			//插入参数
			${classNameFirstWordUpper}Dto ${classNameFirstWordLower}Dto = new ${classNameFirstWordUpper}Dto();
			String adminMan = WebUtils.getUsername();//加入管理员
			String userId = WebUtils.getUserId();
			${classNameFirstWordLower}Dto.setCreatemanId(userId);
			${classNameFirstWordLower}Dto.setCreateman(adminMan);
			${classNameFirstWordLower}Dto.setCompanyId(WebUtils.getCompanyId());
			//插入数据
			<#list columnCanAddList as column>
			${classNameFirstWordLower}Dto.set${column.propertyNameFirstWordUpper}(this.${column.propertyName});
			</#list>

			//调用远程服务
			resultObj =  ${classNameFirstWordLower}Service.addData(${classNameFirstWordLower}Dto);
			<#--if(!resultObj.isSuccess()){
				this.result = "error:"+resultObj.getContent();
				JsonPaginationUtils.responseWriter(response, this.result);
				return "jsonResult";
			}-->
			this.jsonArrayResult.add(resultObj.getResultMap());

		} catch (Exception e) {
			e.printStackTrace();
			resultObj.fault("error:系统出错:"+e.getLocalizedMessage());
			this.jsonArrayResult.add(resultObj.getResultMap());
		}
		return "jsonArray";
	}


	//=====================================================
	// setter getter method
	//=====================================================


<#list columnList as column>
	public String get${column.propertyNameFirstWordUpper}(){
	return ${column.propertyName};
	}
	public void set${column.propertyNameFirstWordUpper}(String ${column.propertyName}){
	this.${column.propertyName} = ${column.propertyName};
	}
	<#if  column.columnType4JavaEncap=='Timestamp' || column.queryType=='between'>
    public String get${column.propertyNameFirstWordUpper}_Start(){
    	return ${column.propertyName}_Start;
    }
    public void set${column.propertyNameFirstWordUpper}_Start(String ${column.propertyName}_Start){
    	this.${column.propertyName}_Start = ${column.propertyName}_Start;
    }
    public String get${column.propertyNameFirstWordUpper}_End(){
    	return ${column.propertyName}_End;
    }
    public void set${column.propertyNameFirstWordUpper}_End(String ${column.propertyName}_End){
    	this.${column.propertyName}_End = ${column.propertyName}_End;
    }
    <#--public String get${column.propertyNameFirstWordUpper}_Str(){
    	return ${column.propertyName}_Str;
    }
    public void set${column.propertyNameFirstWordUpper}_Str(String ${column.propertyName}_Str){
    	this.${column.propertyName}_Str = ${column.propertyName}_Str;
    }-->
	</#if>
</#list>

	public String getSortColumn() {
		return sortColumn;
	}
	public void setSortColumn(String sortColumn) {
		this.sortColumn = sortColumn;
	}
	public String getSortOrder() {
		return sortOrder;
	}
	public void setSortOrder(String sortOrder) {
		this.sortOrder = sortOrder;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	public List<Map<String, Object>> getJsonArrayResult() {
		return jsonArrayResult;
	}
	public void setJsonArrayResult(List<Map<String, Object>> jsonArrayResult) {
		this.jsonArrayResult = jsonArrayResult;
	}

}
